package evs.gateway;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map.Entry;
 
public class HttpHelper {

    public String get( String urlString, String contentType ) throws IOException
	{
		return _request( urlString, "GET", null, contentType );
	}
	
	public String post( String urlString, String content, String contentType ) throws IOException
    {
        return _request( urlString, "POST", content, contentType );
    }
	
	public String put( String urlString, String content, String contentType ) throws IOException
    {
        return _request( urlString, "PUT", content, contentType );
    }
	
	public String delete( String urlString, String content, String contentType ) throws IOException
    {
        return _request( urlString, "DELETE", null, contentType );
    }
	
	public int getLastResponseCode() { return _lastResponseCode; }
	
	public void addCustomHeaderField( String field, String value )
	{
	    _customHeaderFields.put( field, value );
	}
	
	
	//-- PRIVATE HELPER METHODS --------------------------------------------------------------------
	
	private String _request( String urlString, String requestMethod, String content, String contentType ) throws IOException
    {
	    assert requestMethod.equals( "POST" ) ||
	           requestMethod.equals( "GET" ) ||
	           requestMethod.equals( "PUT" ) ||
	           requestMethod.equals( "DELETE" );
	    
        HttpURLConnection connection = null;
        
        try
        {
            URL url = new URL( urlString );
            
            connection = (HttpURLConnection) url.openConnection();
            
            if ( requestMethod.equals( "POST" ) || requestMethod.equals( "PUT" ) )
                connection.setDoOutput( true );
            
            connection.setRequestMethod( requestMethod );
            connection.setRequestProperty( "Content-Type", contentType );
            
            for ( Entry<String, String> entry : _customHeaderFields.entrySet() )
            {
                connection.setRequestProperty( entry.getKey(), entry.getValue() );
            }
            
            connection.connect();
            
            if ( content != null )
            {
                _writeRequestContent( content, connection );
            }
            
            String response = _readResponse( connection );
            
            return response;
        }
        finally
        {
            if ( connection != null )
            {
                _lastResponseCode = connection.getResponseCode();
                connection.disconnect();
            }
        }
    }

    private static void _writeRequestContent( String content, HttpURLConnection connection )
                    throws IOException
    {
        Writer writer = new OutputStreamWriter( connection.getOutputStream() );
        writer.write( content );
        writer.flush();
    }
	
	private static String _readResponse( HttpURLConnection connection ) throws IOException
    {
        BufferedReader rd = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
        StringBuilder text = new StringBuilder();
        
        String line;
        while ((line = rd.readLine()) != null) {
            text.append(line);
            text.append('\n');
        }
        
        text.deleteCharAt( text.length() - 1 );
        
        return text.toString();
    }
	
	private int _lastResponseCode = -1;
	private HashMap<String,String> _customHeaderFields = new HashMap<String, String>();
}
